Skip to main content
Version: 1.0.0

updateProductHelper

Function Name: updateExistingProductDocument

Author: Domenico Cerone Creation Date: 09/10/2025
Last Reviewer: Domenico Cerone

Trigger: Helper function (called by updateVariantProduct)

Purpose: Updates an existing document in the 'Products' Firestore collection using updated mapped JSON data. This function handles complete field refresh and tag regeneration while maintaining workflow fields unchanged.

Detailed Functionalityโ€‹

This helper function performs comprehensive updates to existing Products documents with complete tag regeneration using thread-safe utilities.

1. EXISTING DOCUMENT LOADINGโ€‹

  • Receives productRef as document ID parameter
  • Loads existing document from 'Products' collection
  • If NOT EXISTS โ†’ error (does not create new documents)
  • If EXISTS โ†’ proceeds with update (STEP 2)

2. FIELD UPDATES AND TAG REGENERATIONโ€‹

  • Updates only fields that come from mapped JSON
  • COMPLETELY REGENERATES ALL TAGS (like populateVariantFromSku):
    • Searches/creates tags in Tags collection using tagUtils
    • Thread-safe to avoid duplicates
    • Automatic translations (Gender โ†’ Italian)
    • AUTOMATIC BRAND NORMALIZATION: โ€ข "HUGO" โ†’ "HUGO EYEWEAR" โ€ข "HUGO BOSS", "BOSS ORANGE" โ†’ "BOSS EYEWEAR" โ€ข "CARRERA BY JIMMYCHOO", "CARRERA BIKE", etc. โ†’ "CARRERA" โ€ข "POLAROID KIDS", "POLAROID STAYSAFE", etc. โ†’ "POLAROID" โ€ข "SMITH", "SMITH SNOW", "SUNCLOUD", etc. โ†’ "SMITH OPTICS"
    • Normalized brands for Line tags with correct catalogRef
  • Maintains all existing workflow fields unchanged
  • Maintains variants_map and list_variants existing
  • Updates lastUpdate with current timestamp

Brand Normalization Systemโ€‹

The function includes an intelligent brand normalization system that applies business rules to standardize brand names from SAP data to consistent marketing brand names.

Brand Mapping Rules:

  • Hugo brands: "HUGO" โ†’ "HUGO EYEWEAR"
  • Boss brands: "HUGO BOSS", "BOSS ORANGE" โ†’ "BOSS EYEWEAR"
  • Carrera brands: "CARRERA BY JIMMYCHOO", "CARRERA BIKE", "CARRERA SNOW", "CARRERA DUCATI" โ†’ "CARRERA"
  • Polaroid brands: "POLAROID ANCILLARIES", "POLAROID KIDS", "POLAROID STAYSAFE" โ†’ "POLAROID"
  • Smith brands: "SMITH FASHION & ACC.", "SMITH BIKE HELMETS", "SMITH SNOW", "SMITH BIKE GOGGLES", "PRIVATE LABEL SMITH", "SUNCLOUD" โ†’ "SMITH OPTICS"
  • Other brands: Remain unchanged

Implementation: The mapToNormalizedBrand() function is called automatically during data mapping to ensure consistent brand naming across the Products collection.

Fields Updated from Mapped JSONโ€‹

Base Product Fields:

  • age โ† catAgeForGender
  • manufacturedProductStatus โ† manufacturedProductStatus
  • rxAble โ† rxAble (converted from "YES"/"NO" to boolean)
  • mainBrandRef โ† brand ID (searches/creates in MainBrands collection)
  • upcCode โ† upcCode
  • imgUrl โ† poster (first image from current variant)
  • thumbnail โ† poster (first image from current variant)
  • urlImage โ† poster (first image from current variant)

Timestamp Fields:

  • lastUpdate โ† current timestamp
  • productReleaseDate โ† productReleaseDate (if present)
  • productEndDate โ† productEndDate (if present)

Multilingual Descriptions:

  • descriptionEn โ† description_en
  • descriptionIt โ† description_it
  • descriptionEs โ† description_es
  • descriptionFr โ† description_fr
  • descriptionDe โ† description_de

Tags Arrays (regenerated from mapped JSON):

  • list_frame_color_tags โ† [frameColor tag IDs from Tags collection]
  • list_size_tags โ† [size tag IDs from Tags collection]
  • list_line_tags โ† [line tag IDs linked to normalized brand] INPUT: mappedData.mainBrandRef="HUGO BOSS", mappedData.nomeLinea="BOSS ORANGE SPORT" STEP 1: Search/create BRAND in MainBrands: "HUGO BOSS" โ†’ normalize โ†’ "BOSS EYEWEAR" โ†’ brandId STEP 2: Search/create LINE TAG in Tags: name="BOSS ORANGE SPORT" + catalogRef=brandId OUTPUT: ["tag456def"] - Line tag ID linked to normalized brand
  • list_tags โ† [catType, catAgeForGender, catGender, catForma, catMaterialOne, polarised (as tag ID), catLensesTreat, hingeType]

Fields Maintained Unchangedโ€‹

All other fields of the existing document remain unchanged:

  • modelName (primary identifier)
  • variants_map (existing variant management)
  • list_variants (existing variant IDs)
  • availableVariants (existing count)
  • All workflow and configuration fields

Tag Creation Functionsโ€‹

The function uses specialized thread-safe tag creation functions:

Frame Color Tags:

  • findOrCreateFrameColorTag() - Creates/finds tags with type "Frame Color"

Size Tags:

  • findOrCreateSizeTag() - Creates/finds tags with type "Size"

Line Tags:

  • findOrCreateLineTag() - Creates/finds tags with type "Line" and catalogRef to brand

Category Tags:

  • findOrCreateCatTypeTag() - Creates/finds "Tipologia" tags
  • findOrCreateCatAgeForGenderTag() - Creates/finds "Age For Gender" tags
  • findOrCreateCatGenderTag() - Creates/finds "Gender" tags with Italian translation
  • findOrCreateCatFormaTag() - Creates/finds "Forma" tags
  • findOrCreateCatMaterialOneTag() - Creates/finds "Materiale" tags
  • findOrCreatePolarisedTag() - Creates/finds "Polarised" tags
  • findOrCreateCatLensesTreatTag() - Creates/finds "Treatement" tags
  • findOrCreateHingeTypeTag() - Creates/finds "Hinge Type" tags

Input Parametersโ€‹

Function Signature:

async function updateExistingProductDocument(productRef, mappedJsonData, requestId)

Parameters:

  • productRef (string, required): ID of the Products document to update
  • mappedJsonData (Object, required): Updated mapped JSON data
  • requestId (string, required): Request ID for logging

Expected mappedJsonData Structure:

This data comes from the main function after processing the CatalogOrder document and downloading/mapping fresh data from Safilo APIs:

{
"mapped_data": {
"catAgeForGender": "ADULT",
"manufacturedProductStatus": "ACTIVE",
"rxAble": "YES",
"mainBrandRef": "HUGO BOSS",
"upcCode": "762753916013",
"poster": "https://firebasestorage.googleapis.com/...",
"description_en": "Modern sunglasses",
"description_it": "Occhiali da sole moderni",
"frameColor": "BLACK",
"size": "54",
"nomeLinea": "BOSS ORANGE SPORT",
"catType": "SUNGLASSES FRAMES",
"catGender": "WOMAN",
"catForma": "ROUND",
"catMaterialOne": "ACETATE",
"polarised": "YES",
"catLensesTreat": "GRADIENT",
"hingeType": "FLEX",
"productReleaseDate": 1640995200000,
"productEndDate": 1672531200000
}
}

Output (Success)โ€‹

{
"success": true,
"operation": "update",
"documentId": "existing_product_id",
"modelName": "BOSS 1234/S",
"message": "Documento Products aggiornato per ID existing_product_id",
"updatedFields": [
"age",
"manufacturedProductStatus",
"rxAble",
"mainBrandRef",
"upcCode",
"imgUrl",
"thumbnail",
"urlImage",
"lastUpdate",
"descriptionEn",
"descriptionIt",
"list_frame_color_tags",
"list_size_tags",
"list_line_tags",
"list_tags",
"productReleaseDate",
"productEndDate"
]
}

Output (Error)โ€‹

{
"success": false,
"operation": "error",
"documentId": "existing_product_id",
"modelName": "UNKNOWN",
"message": "Errore nell'aggiornamento documento Products: Document not found",
"error": "Document not found"
}
  • Main Function: updateVariantProduct - Main function that calls this helper
  • Variant Helper: updateVariantHelper - Parallel helper for Variants collection
  • Tag Utilities: tagUtils - Thread-safe tag creation utilities with mutex synchronization to prevent duplicates

Error Handlingโ€‹

The function includes comprehensive error handling:

  • Document Not Found: Returns error if productRef doesn't exist
  • Invalid Data: Validates mappedJsonData structure
  • Tag Creation Errors: Continues operation even if some tags fail
  • Firestore Errors: Catches and logs database operation errors
  • Brand Creation Errors: Falls back to empty string if brand operations fail

Performance Considerationsโ€‹

  • Thread-Safe Operations: All tag operations use mutex synchronization
  • Batch Tag Creation: Multiple tags created efficiently in parallel
  • Minimal Database Writes: Only updates changed fields
  • Error Isolation: Individual tag failures don't block document update